/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.yunyichina.provider.framework.annotation.validate;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;

/**
 * Validate the @int annotation
 *
 * @author jiangtch
 */
public class ValidateIntHandler implements Handler {

    private static final Logger logger = LoggerFactory.getLogger(ValidateIntHandler.class);

    public void validate(AnnotationValidable validatedObj, Field field) throws ValidateException {
        if (logger.isTraceEnabled()) {
            logger.trace(this.getClass().getName(), "validate()");
        }
        if (field.isAnnotationPresent(ValidateInt.class)) {
            checkInt(validatedObj, field);
        }
    }

    /**
     * validate the int type
     *
     * @param filter validated object
     * @param field  validated field or property
     * @throws ValidateException
     */
    private void checkInt(AnnotationValidable filter, Field field) throws ValidateException {
        if (logger.isTraceEnabled()) {
            logger.trace(this.getClass().getName(), "checkInt()");
        }
        ValidateInt annotation = field.getAnnotation(ValidateInt.class);
        int min = annotation.min();
        int max = annotation.max();
        Integer destValue;
        try {
            Object obj = GetFiledValue.getField(filter, field.getName());
            if (obj == null) {
                return;
            }
            destValue = Integer.valueOf(String.valueOf(GetFiledValue.getField(filter, field.getName())));
        } catch (Exception ex) {
            logger.error("字段：" + field.getName() + " 获取值发生异常->" + ex.getMessage(), ex);
            throw new ValidateException("字段：" + field.getName() + " 获取值发生异常->" + ex.getMessage(), ex);
        }
        if (destValue == null) {
            return;
        }
        int value = destValue.intValue();
        if (value < min) {
            logger.warn("字段：" + field.getName() + " 数据校验失败,当前值为" + value + ",最小值为:" + min + ",请检查!");
            throw new ValidateException("字段：" + field.getName() + " 数据校验失败,当前值为" + value + ",最小值为:" + min + ",请检查!");
        }
        if (value > max) {
            logger.warn("字段：" + field.getName() + " 数据校验失败,当前值为" + value + ",最大值为:" + max + ",请检查!");
            throw new ValidateException("字段：" + field.getName() + " 数据校验失败,当前值为" + value + ",最大值为:" + max + ",请检查!");
        }
    }

}
